package com.bfly.mall.tasks;

import com.bfly.core.context.event.ScheduledTaskExecCompleteEvent;
import com.bfly.core.security.ScheduledInfo;
import com.bfly.mall.product.service.IProductSecKillService;
import com.bfly.mall.tasks.entity.ScheduledTaskExecResult;
import com.bfly.mall.tasks.service.IScheduled;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Calendar;

/**
 * 产品定时任务
 *
 * @author 长沙商脉科技有限公司
 * @date 2021/8/4 17:31
 */
@Configuration
public class ProductTask extends AbstractScheduledTask implements IScheduled {

    @Autowired
    private IProductSecKillService productSecKillService;
    private final String PRODUCT_SEC_KILL_STATUS = "product_sec_kill_status";
    private final String PRODUCT_SEC_KILL_STATUS_CRON = "0 0/1 * * * ?";

    /**
     * 定时检查秒杀产品活动状态
     *
     * @author 长沙商脉科技有限公司
     * @date 2021/8/4 17:32
     */
    @Scheduled(cron = PRODUCT_SEC_KILL_STATUS_CRON)
    @ScheduledInfo(name = PRODUCT_SEC_KILL_STATUS, remark = "每1分钟执行一次,检查秒杀产品活动状态!")
    public void checkCompleteProductSecKill() {
        if (!allowRun(PRODUCT_SEC_KILL_STATUS)) {
            return;
        }
        String message = "执行成功!";
        try {
            productSecKillService.editCompleteSecKill();
        } catch (Exception e) {
            message = e.getMessage();
        }
        ScheduledTaskExecResult result = new ScheduledTaskExecResult(PRODUCT_SEC_KILL_STATUS, PRODUCT_SEC_KILL_STATUS_CRON, Calendar.getInstance().getTime(), message);
        executeCompletedEvent(new ScheduledTaskExecCompleteEvent(result));
    }
}